<template>
  <div>
    <a-modal
      v-model:open="nameOpen"
      title="目前管理方案"
      :width="450"
      @ok="handleOk"
      :maskClosable="false"
    >
      <a-row>
        <a-col :span="7">
          <span style="height: 32px; line-height: 32px">已配置管理方案</span>
        </a-col>
        <a-col :span="17">
          <a-space
            v-for="(item, index) of programmeList"
            :key="index"
            style="margin-bottom: 8px; width: 100%"
          >
            <a-input readonly :disabled="item.status == 1" v-model:value="item.planName"></a-input>
            <a @click="newProgramme(item, 'detail')">查看详情</a>
          </a-space>
        </a-col>
      </a-row>
      <template #footer>
        <a-button
          key="back"
          v-auth="'hp-admin:patientManagement:manageConfig'"
          @click="newProgramme"
          >新增</a-button
        >
        <a-button key="submit" type="primary" @click="nameOpen = false">确定</a-button>
      </template>
    </a-modal>
    <a-modal v-model:open="toolOpen" title="提示" :width="410" @ok="handleOk" :maskClosable="false">
      <p>当前管理方案内容较所选模板发生改变，请为其编辑新的管理方案名称:</p>
      <a-input placeholder="请输入新的管理方案名称" v-model:value="programmeName"></a-input>
      <p style="color: #ff7d00; margin-top: 16px">确认后管理方案自动存为新模板</p>
      <template #footer>
        <a-button key="back" @click="cancelProgramme">取消</a-button>
        <a-button key="submit" type="primary" @click="saveProgramme">确定</a-button>
      </template>
    </a-modal>
    <a-modal
      v-model:open="modal.open"
      :title="modal.title"
      @ok="handleOk"
      :width="1200"
      :bodyStyle="{
        'max-height': modelMaxHeight,
        overflow: 'auto'
      }"
      :maskClosable="false"
    >
      <a-form
        class="modelForm"
        ref="modelForm"
        :colon="false"
        :model="formState"
        :label-col="{ style: { width: '140px' } }"
      >
        <!-- <a-form-item
          v-if="modal.type === 'detail'"
          :label-col="{ style: { width: '110px' } }"
          label="已配置专病分组"
        >
          <a-tag color="processing" v-for="(item, i) in formState.groupNames" :key="i">{{
            item
          }}</a-tag>
        </a-form-item> -->
        <a-form-item
          label="管理方案名称"
          :label-col="{ style: { width: '110px' } }"
          name="planName"
          required
          :rules="{
            required: true,
            message: '管理方案名称不能为空',
            trigger: 'change'
          }"
        >
          <a-input
            v-if="modal.type === 'detail'"
            style="width: 350px"
            v-model:value="formState.planName"
            :disabled="modal.type === 'detail'"
          ></a-input>
          <a-auto-complete
            v-else
            style="width: 350px"
            :maxlength="50"
            placeholder="请输入管理方案名称"
            :options="getName(manageList)"
            v-model:value="formState.planName"
            @select="onSelect"
            @search="onSearch"
            :getPopupContainer="(triggerNode) => triggerNode.parentNode"
          ></a-auto-complete>
          <a-space class="programme_date">
            <span class="date">更新时间</span>
            <span class="datetime">{{ updateTime }}</span>
            <span class="date">配置时间</span>
            <span class="datetime">{{ configTime }}</span>
          </a-space>
        </a-form-item>
        <a-form-item>
          <a-row class="title">
            <a-col :span="24">
              <span class="red">*</span>
              管理路径编辑
            </a-col>
          </a-row>
        </a-form-item>
        <div class="bar">
          <a-form-item
            label="管理路径触发事件"
            name="isIn"
            :rules="{
              required: true,
              message: '请完善触发事件',
              trigger: 'change'
            }"
          >
            <a-radio-group
              v-model:value="formState.isIn"
              @change="isInChange"
              name="radioGroup"
              :disabled="modal.type === 'detail'"
            >
              <a-radio :value="1">入组前发生事件</a-radio>
              <a-radio :value="2">入组后发生事件</a-radio>
              <a-radio :value="3">入组即执行</a-radio>
            </a-radio-group>
          </a-form-item>
          <div style="padding-left: 140px" label=" " v-if="[1, 2].includes(formState.isIn)">
            <a-row :gutter="[16, 0]">
              <a-col>
                <a-form-item
                  name="eventType"
                  :rules="{
                    required: true,
                    message: '请选择事件类型',
                    trigger: 'change'
                  }"
                >
                  <a-select
                    v-model:value="formState.eventType"
                    @change="eventTypeChange"
                    style="width: 96px"
                    :disabled="modal.type === 'detail'"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                  >
                    <a-select-option
                      v-for="option in eventMaps"
                      :value="option.value"
                      :key="option.value"
                      >{{ option.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col v-if="[1, 2, 3, 4, 5, 6].includes(formState.eventType)">
                <a-form-item
                  name="event"
                  :rules="{
                    required: true,
                    message: '请完善事件内容',
                    trigger: 'change'
                  }"
                >
                  <!-- <a-input
                    style="width: 382px"
                    v-model:value="formState.event"
                    autocomplete="off"
                    placeholder="请输入事件名称"
                    :disabled="modal.type === 'detail'"
                  ></a-input> -->
                  <a-auto-complete
                    v-model:value="formState.event"
                    :options="dictData"
                    :style="{ width: '382px' }"
                    :disabled="modal.type == 'detail'"
                    placeholder="请输入事件名称"
                    :filterOption="
                      (inputValue, option) =>
                        option.value.toUpperCase().indexOf(formState.event.toUpperCase()) >= 0
                    "
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                    :listHeight="200"
                  >
                  </a-auto-complete>
                </a-form-item>
              </a-col>
              <a-col v-if="[4, 5, 7].includes(formState.eventType)" style="padding-top: 6px"
                >结果</a-col
              >
              <a-col v-if="[4, 5, 7].includes(formState.eventType)">
                <a-select
                  v-model:value="formState.compare"
                  style="width: 60px"
                  :disabled="modal.type === 'detail'"
                  :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                >
                  <a-select-option value="=">{{ '=' }}</a-select-option>
                  <a-select-option value=">">{{ '>' }}</a-select-option>
                  <a-select-option value="≥">{{ '≥' }}</a-select-option>
                  <a-select-option value="<">{{ '<' }}</a-select-option>
                  <a-select-option value="≤">{{ '≤' }}</a-select-option>
                  <a-select-option value="≠">{{ '≠' }}</a-select-option>
                </a-select>
              </a-col>
              <a-col v-if="[4, 5, 7].includes(formState.eventType)">
                <a-form-item
                  name="result"
                  :rules="[
                    {
                      required: true,
                      message: '请完善事件内容',
                      trigger: 'change'
                    }
                  ]"
                >
                  <a-input
                    style="width: 348px"
                    v-model:value="formState.result"
                    autocomplete="off"
                    placeholder="请输入结果描述"
                    :disabled="modal.type === 'detail'"
                  ></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </div>
          <a-form-item
            label="上述事件发生后"
            v-if="[1, 2].includes(formState.isIn)"
            name="offset"
            :rules="{
              validator: validator_offset
            }"
          >
            <a-row :gutter="[8, 0]">
              <a-col>
                <a-input
                  v-model:value="formState.offset"
                  @input="formState.offset = $event.target.value.replace(/[^0-9]/g, '')"
                  style="width: 96px"
                  autocomplete="off"
                  :disabled="modal.type === 'detail'"
                ></a-input>
              </a-col>
              <a-col style="display: flex; align-items: center">
                <a-radio-group
                  v-model:value="formState.unit"
                  name="radioGroup"
                  :disabled="modal.type === 'detail'"
                >
                  <a-radio :value="1">年</a-radio>
                  <a-radio :value="2">月</a-radio>
                  <a-radio :value="3">日</a-radio>
                </a-radio-group>
              </a-col>
              <a-col style="display: flex; align-items: center">开始执行下方管理任务</a-col>
            </a-row>
          </a-form-item>
        </div>
        <div class="node" v-for="(subitem, i) in formState.managePlanNodeEntity" :key="i">
          <a-form-item>
            <a-row class="title">
              <a-col :span="20"> 管理节点{{ i + 1 }} </a-col>
              <a-col :span="4" style="text-align: right">
                <a-button
                  v-if="modal.type !== 'detail'"
                  type="link"
                  parmary
                  style="padding-right: 0"
                  @click="copyNode(i, formState.managePlanNodeEntity)"
                  >复制节点</a-button
                >
                <a-button
                  v-if="modal.type !== 'detail'"
                  type="link"
                  danger
                  @click="del(i, formState.managePlanNodeEntity)"
                  >删除节点</a-button
                >
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item
            label="进入管理路径后"
            :label-col="{ style: { width: '130px' } }"
            :name="['managePlanNodeEntity', i]"
            :rules="{
              validator: validator_node
            }"
          >
            <a-row :gutter="[8, 0]">
              <a-col :span="4">
                <a-input-number
                  min="1"
                  :precision="0"
                  :step="1"
                  style="width: 96px"
                  v-model:value="subitem.pathDay"
                  autocomplete="off"
                  :disabled="modal.type === 'detail'"
                  @change="pathDayChange($event, subitem, 'managePlanNodeEntity')"
                ></a-input-number>
                天
              </a-col>
              <a-col :span="2" style="line-height: 32px">管理行为</a-col>
              <a-col :span="18">
                <a-row :gutter="[8, 8]">
                  <template v-for="(item, index) in subitem.behaviorJson" :key="index">
                    <a-col>
                      <a-form-item-rest>
                        <a-select
                          v-model:value="item.type"
                          style="width: 120px"
                          @change="tempTypeChange($event, item)"
                          :disabled="modal.type === 'detail'"
                          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                        >
                          <a-select-option v-for="t in tempMaps" :value="t.value" :key="t.label">{{
                            t.label
                          }}</a-select-option>
                        </a-select>
                      </a-form-item-rest>
                    </a-col>
                    <a-col style="width: calc(100% - 144px)" class="row">
                      <a-form-item-rest>
                        <a-tooltip placement="top">
                          <template v-if="item.template_id" #title>{{
                            item.template_name
                          }}</template>
                          <a-select
                            v-model:value="item.template_id"
                            showSearch
                            optionFilterProp="label"
                            :placeholder="placeholderMsg(item.type)"
                            @change="
                              templateChange(
                                $event,
                                TemplateList[item.type],
                                item,
                                subitem.pathDay,
                                ['managePlanNodeEntity', i]
                              )
                            "
                            :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                            :disabled="modal.type === 'detail'"
                            style="width: 80%"
                          >
                            <a-select-option
                              v-for="t in item.type ? TemplateList[item.type] : []"
                              :value="t.id"
                              :key="t.id"
                              :label="t.templateName"
                              >{{ t.templateName }}</a-select-option
                            >
                          </a-select>
                        </a-tooltip>
                      </a-form-item-rest>
                      <a-col v-if="(item.type === 1 || item.type === 2) && modal.type !== 'detail'">
                        <a-button type="link" @click="addContent(item, index, i)"
                          >新增模板</a-button
                        >
                      </a-col>
                      <a-col v-if="modal.type !== 'detail'">
                        <icon-font
                          v-if="index"
                          class="icon-del"
                          @click="del(index, subitem.behaviorJson)"
                          type="icon-shanchu"
                        />
                        <icon-font
                          v-else
                          class="icon-plus"
                          @click="addOptions(subitem.behaviorJson)"
                          type="icon-xinzeng"
                        />
                      </a-col>
                    </a-col>
                  </template>
                </a-row>
              </a-col>
            </a-row>
          </a-form-item>
        </div>
        <a-form-item v-if="modal.type == 'save'">
          <a-row>
            <a-button
              style="width: 100%; color: #165dff; border-color: #165dff"
              :icon="h(PlusOutlined)"
              @click="addEventBtn({}, 'new')"
            >
              新增管理节点
            </a-button>
          </a-row>
        </a-form-item>
      </a-form>
      <template #footer>
        <template v-if="modal.type == 'detail'">
          <a-popconfirm
            v-if="programmeStatus == 0"
            ok-text="确定"
            ok-type="danger"
            cancel-text="取消"
            @confirm="confirmStop"
            @cancel="cancel"
          >
            <template #icon>
              <InfoCircleOutlined style="color: red" />
            </template>
            <template #title>
              <b>停止执行</b>
              <p>确定停止执行么？</p>
            </template>
            <a-button danger>停止执行</a-button>
          </a-popconfirm>
          <a-button v-else disabled>已停止执行</a-button>
          <a-button key="back" type="primary" @click="modal.open = false">确认</a-button>
        </template>
        <template v-else>
          <a-button key="back" @click="modal.open = false">取消</a-button>
          <a-button type="primary" :loading="btnLoading" @click="addConfirm">确定</a-button>
        </template>
      </template>
    </a-modal>

    <a-modal v-model:open="isAddContent" :title="contentTitle" :width="800" :maskClosable="false">
      <a-form ref="formRef" :model="templateForm" :rules="formRules">
        <a-form-item
          :label="chosenState.type == '2' ? '健康提醒名称' : '健康教育名称'"
          name="formName"
        >
          <a-input
            v-model:value="templateForm.formName"
            :placeholder="chosenState.type == '2' ? '请输入健康提醒名称' : '请输入健康教育处方名称'"
          ></a-input>
        </a-form-item>
        <a-form-item label="健康提醒类型" name="remindType" v-if="chosenState.type == '2'">
          <a-select v-model:value="templateForm.remindType">
            <a-select-option value="1">用药提醒</a-select-option>
            <a-select-option value="2">复查提醒</a-select-option>
            <a-select-option value="3">其他提醒</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :label="chosenState.type == '2' ? '健康提醒内容' : '健康教育内容'"
          name="context"
        >
          <a-textarea
            v-model:value="templateForm.context"
            :placeholder="chosenState.type == '2' ? '请输入健康提醒内容' : '请输入健康教育内容'"
            show-count
            :maxlength="chosenState.type == '2' ? 300 : 5000"
            :auto-size="{ minRows: chosenState.type == '2' ? 4 : 8 }"
          ></a-textarea>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="isAddContent = false">取消</a-button>
        <a-button type="primary" @click="saveTemplate" :loading="templateLoading"
          >存为模板</a-button
        >
      </template>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { Dayjs } from 'dayjs'
import { reactive, ref, toRaw, onMounted, h, createVNode } from 'vue'
import type { UnwrapRef } from 'vue'
import type { Rule } from 'ant-design-vue/es/form'
import { message, Modal } from 'ant-design-vue'
import {
  PlusOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
  InfoCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'
import _ from 'lodash'
import { getTemplateList, saveTemplateForm } from '@/api/patientManagement/index.ts'
import {
  getListByGroup,
  getManagePlanInfo,
  stopManagePlan
} from '@/api/patientManagement/programme.ts'
import { getTemplateMaps, PlanSave, getPlanList } from '@/api/templateManage'
import { getEventName } from '@/api/patientManagement/ai-group.ts'
interface FormState {}

const props = defineProps(['groupId'])
const emit = defineEmits(['close'])

const formRef = ref()
const btnLoading = ref(false)
const checked = ref(false)
const isReadonly = ref(false)
const programmeName = ref('')
const updateTime = ref('—')
const configTime = ref('—')
const programmeStatus = ref('')

const modelMaxHeight = ref(window.innerHeight * 0.8 - 150 + 'px')

const modal = reactive({
  open: false,
  type: 'save',
  loading: false,
  title: '新增管理方案'
})

const isAddContent = ref(false)
const templateLoading = ref(false)
const contentTitle = ref('')
const chosenState = ref({})

const dictData = ref([])

const formState: UnwrapRef<FormState> = reactive({
  id: '',
  planName: '',
  isIn: 3,
  eventType: '',
  event: '',
  compare: '=',
  result: '',
  offset: '',
  unit: '',
  // plan_type: 1,
  managePlanNodeEntity: [
    {
      pathDay: '',
      behaviorJson: [
        {
          type: 1,
          template_name: '',
          template_id: ''
        }
      ]
    }
  ]
})
const templateForm: any = reactive({
  formName: '',
  remindType: '2',
  context: ''
})

const formRules = ref({
  formName: [
    {
      required: true,
      message: chosenState.type == '2' ? '请输入健康提醒名称' : '请输入健康教育处方名称',
      trigger: 'blur'
    }
  ],
  remindType: [{ required: true, message: '请选择健康提醒类型', trigger: 'change' }],
  context: [{ required: true, message: '请选择输入健康提醒内容', trigger: 'blur' }]
})

const nameOpen = ref<boolean>(false)
const toolOpen = ref<boolean>(false)

// 方案列表
const programmeList = ref([])
const eventMaps = [
  {
    label: '诊断',
    value: 1
  },
  {
    label: '药品',
    value: 2
  },
  {
    label: '手术',
    value: 3
  },
  {
    label: '检验',
    value: 4
  },
  {
    label: '检查',
    value: 5
  },
  {
    label: '性别',
    value: 6
  },
  {
    label: '年龄',
    value: 7
  }
]

const tempMaps = [
  {
    label: '健康教育',
    value: 1
  },
  {
    label: '健康提醒',
    value: 2
  },
  {
    label: 'AI随访',
    value: 3
  },
  {
    label: '人工随访',
    value: 4
  }
]
// 节点列表
const eventList = reactive([])
const TemplateList = ref([])
const manageList = ref([])
const initFormState = ref({})

const modelForm = ref(null)

const init = () => {
  nameOpen.value = true
  getGroupData()
}
const getGroupData = () => {
  let params = {
    groupId: props.groupId
  }
  getListByGroup(params).then((res) => {
    console.log('groupId', res.data)
    programmeList.value = res.data
  })
}

const getTempList = async () => {
  await getTemplateMaps()
    .then((res) => {
      TemplateList.value = res.data
    })
    .catch((e) => {})
}

const eventTypeChange = async (e) => {
  formState.event = ''
  formState.compare = '='
  formState.result = ''

  dictData.value = []

  let eventId: any = ''
  switch (e) {
    case 1:
      eventId = 1
      break
    case 2:
      eventId = 2
      break
    case 3:
      eventId = 3
      break
    case 4:
      eventId = 4
      break
    case 5:
      eventId = 5
      break
    default:
      eventId = 0
      break
  }

  if (eventId) {
    await getEventName({ dictTypeId: eventId }).then((res) => {
      dictData.value = res.data
    })
  }
}

const filterOption = (input: string, option: Option) => {
  return option.value.toUpperCase().indexOf(input.toUpperCase()) >= 0
}

// 重置表单数据
const formState_reset = (item) => {
  if (item) {
    Object.assign(formState, item)
    initFormState.value = JSON.stringify(formState)
  } else {
    initFormState.value = JSON.stringify({})
    Object.assign(formState, {
      id: '',
      planName: '',
      isIn: 3,
      eventType: '',
      event: '',
      compare: '=',
      result: '',
      offset: '',
      unit: '',
      // plan_type: 1,
      managePlanNodeEntity: [
        {
          pathDay: '',
          behaviorJson: [
            {
              type: 1,
              template_name: '',
              template_id: undefined
            }
          ]
        }
      ]
    })
  }
}

const newProgramme = (item: any, type: string) => {
  modelForm.value?.clearValidate()
  if (type == 'detail') {
    getManagePlanInfo({ id: item.id }).then((res) => {
      if (res) {
        const obj = _.cloneDeep(res.data)
        obj.managePlanNodeEntity.map((v) => {
          v.behaviorJson = JSON.parse(v.behaviorJson)
        })
        formState_reset(obj)
        updateTime.value = res.data.createTime
        configTime.value = item.createTime
        programmeStatus.value = item.status
      }
    })
    modal.title = '管理方案详情'
    modal.type = 'detail'
    isReadonly.value = true
  } else {
    modal.title = '新增管理方案'
    modal.type = 'save'
    updateTime.value = '—'
    configTime.value = '—'
    formState_reset()
    isReadonly.value = false
  }
  modal.open = true
  nameOpen.value = false
  getTempList()
}

const handleOk = () => {
  console.log(eventList)
}
// 查询模板方案
const onSearch = _.debounce((searchText: string) => {
  let params = {
    limit: 50,
    page: 1,
    planName: searchText
  }
  getPlanList(params).then((res) => {
    manageList.value = res.data.list
  })
}, 500)
// 选择模板方案并赋值
const onSelect = (value: string) => {
  let item = _.filter(manageList.value, (val) => {
    return val.planName == value
  })[0]
  const obj = _.cloneDeep(item)
  obj.managePlanNodeEntity.map((v) => {
    v.behaviorJson = JSON.parse(v.behaviorJson)
  })
  console.log('onSelect', value)
  formState_reset(obj)
}
const getName = (arr) => {
  let newArr = []
  arr.map((item) => {
    newArr.push({ value: item.planName })
  })
  return newArr
}

// 入组
const addEventBtn = (item: any, type: string) => {
  formState.managePlanNodeEntity.push({
    pathDay: '',
    behaviorJson: [
      {
        type: 1,
        template_name: '',
        template_id: undefined
      }
    ]
  })
}

const copyNode = (i, list) => {
  const node = _.cloneDeep(list[i])
  list.splice(i, 0, node)
}

const confirmStop = () => {
  formState.groupId = props.groupId
  stopManagePlan(formState).then((res) => {
    if (res.code == 0) {
      message.success('停止执行成功')
      modal.open = false
      emit('close')
    }
  })
}
const cancel = (e) => {
  console.log(e)
}
const isInChange = (e) => {
  if (e.target.value == 3) {
    formState.eventType = ''
    formState.event = ''
    formState.offset = ''
    formState.unit = ''
  }
}

const pathDayChange = (e, item, name) => {
  item.pathDay = e

  formState.managePlanNodeEntity.forEach((ele, index) => {
    modelForm.value.validate([[name, index]])
  })
}

const placeholderMsg = (index) => {
  let msg = ''
  switch (index) {
    case 1:
      msg = '请选择健康教育内容'
      break
    case 2:
      msg = '请选择健康提醒内容'
      break
    default:
      msg = '请选择随访内容'
  }
  return msg
}

const templateChange = (e, list, item, day, name) => {
  const t = list.find((v) => {
    return v.id === e
  })
  item.template_name = t.templateName
  item.remind_type = t.remindType
  item.context = t.context
  modelForm.value.validate([name])
  // let param = {
  //   pathDay: '',
  //   behaviorJson: []
  // }
  // param.pathDay = day
  // param.behaviorJson.push(item)
  // validator_node('-', param)
}
const tempTypeChange = (e, item) => {
  item.template_id = undefined
  item.template_name = ''
}

// 管理行为部分
const nameSelect = (item) => {
  item.templateData.forEach((val) => {
    if (item.runData.templateName == val.templateName) {
      item.runData.templateName = val.templateName
      item.runData.templateType = val.templateType
      item.runData.remindType = val.remindType
      // item.runData.patId = patRunId.value
      item.runData.type = item.type
      item.runData.context = val.context
    }
  })
}
const templateTypeChange = (item) => {
  item.templateData.forEach((val) => {
    if (item.runData.templateName == val.templateName) {
      item.runData = {
        // patId: patRunId.value,
        type: item.type,
        templateType: val.templateType,
        templateName: val.templateName,
        context: val.context
      }
    }
  })
}
const del = (index, item) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确认是否删除',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      console.log('OK')
      item.splice(index, 1)
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const addOptions = (item) => {
  item.push({
    type: 1,
    template_name: '',
    template_id: undefined
  })
}

const behaviorTemplateIndex = ref()
const manaIndex = ref()
// 新增模板部分
const addContent = (item: any, index, num) => {
  behaviorTemplateIndex.value = index
  manaIndex.value = num
  console.log('item', item)
  isAddContent.value = true
  chosenState.value = item

  switch (item.type) {
    case 1:
      contentTitle.value = '新建健康教育处方'
      break
    case 2:
      contentTitle.value = '新建健康提醒'
      break
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const saveTemplate = () => {
  templateLoading.value = true
  formRef.value
    .validate()
    .then(() => {
      const data = {
        templateType: chosenState.value.type,
        templateName: templateForm.formName,
        context: JSON.stringify({ content: templateForm.context }),
        remindType: templateForm.remindType ? templateForm.remindType : ''
      }
      saveTemplateForm(data)
        .then(async () => {
          message.success('模板保存成功')
          isAddContent.value = false
          templateLoading.value = false
          await getTempList()
          formState.managePlanNodeEntity[manaIndex.value].behaviorJson[
            behaviorTemplateIndex.value
          ].template_id =
            TemplateList.value[
              formState.managePlanNodeEntity[manaIndex.value].behaviorJson[
                behaviorTemplateIndex.value
              ].type
            ][0].id

          formState.managePlanNodeEntity[manaIndex.value].behaviorJson[
            behaviorTemplateIndex.value
          ].template_name =
            TemplateList.value[
              formState.managePlanNodeEntity[manaIndex.value].behaviorJson[
                behaviorTemplateIndex.value
              ].type
            ][0].templateName
          formState.managePlanNodeEntity[manaIndex.value].behaviorJson[
            behaviorTemplateIndex.value
          ].context = JSON.stringify({ content: templateForm.context })

          console.log(formState.managePlanNodeEntity)
        })
        .catch(() => {
          templateLoading.value = false
        })
    })
    .catch(() => {
      templateLoading.value = false
    })
}

const addConfirm = () => {
  modal.loading = true
  modelForm.value
    .validate()
    .then(() => {
      if (!formState.managePlanNodeEntity.length) {
        return Promise.reject('请添加至少一个管理节点')
      }
      if (formState.managePlanNodeEntity.length > 1) {
        const set = new Set(Array.from(formState.managePlanNodeEntity.map((v) => v.pathDay)))
        if (set.size < formState.managePlanNodeEntity.length) {
          message.error('存在时间重复管理节点，请确认')
          modal.loading = false
          return
        }
      }
      console.log('表单验证通过', formState.managePlanNodeEntity)
      console.log(initFormState.value)
      // console.log(JSON.stringify(formState))

      if (Object.getOwnPropertyNames(JSON.parse(initFormState.value)).length == 0) {
        let params = _.cloneDeep(formState)
        params.managePlanNodeEntity
          .sort((f1, f2) => f1.pathDay - f2.pathDay)
          .map((v) => {
            v.behaviorJson = JSON.stringify(v.behaviorJson)
          })
        params.groupId = props.groupId
        PlanSave(params)
          .then((res) => {
            message.success('关联成功')
            modal.open = false
            emit('close')
          })
          .catch((e) => {
            modal.loading = false
          })
      } else if (initFormState.value === JSON.stringify(formState)) {
        let params = _.cloneDeep(formState)
        params.managePlanNodeEntity
          .sort((f1, f2) => f1.pathDay - f2.pathDay)
          .map((v) => {
            v.behaviorJson = JSON.stringify(v.behaviorJson)
          })
        params.groupId = props.groupId
        PlanSave(params)
          .then((res) => {
            message.success('关联成功')
            modal.open = false
            emit('close')
          })
          .catch((e) => {
            modal.loading = false
          })
      } else {
        const paramsinitForm = _.cloneDeep(JSON.parse(initFormState.value))
        delete paramsinitForm.planName
        const paramsForm = _.cloneDeep(formState)
        delete paramsForm.planName

        if (JSON.stringify(paramsinitForm) === JSON.stringify(paramsForm)) {
          let params = _.cloneDeep(formState)
          params.managePlanNodeEntity
            .sort((f1, f2) => f1.pathDay - f2.pathDay)
            .map((v) => {
              v.behaviorJson = JSON.stringify(v.behaviorJson)
            })
          params.groupId = props.groupId
          params.id = null

          PlanSave(params)
            .then((res) => {
              message.success('关联成功')
              let param = {
                limit: 10,
                page: 1,
                planName: programmeName.value
              }
              modal.open = false
              getPlanList(param).then((res) => {
                let item = res.data.list[0]
                const obj = _.cloneDeep(item)
                obj.managePlanNodeEntity.map((v) => {
                  v.behaviorJson = JSON.parse(v.behaviorJson)
                })
                formState_reset(obj)
                toolOpen.value = false
                // modal.open = true
                programmeName.value = ''
              })
            })
            .catch((e) => {
              modal.loading = false
            })
        } else {
          modal.open = false
          toolOpen.value = true
        }
      }
      modal.loading = false
    })
    .catch((e) => {
      modal.loading = false
      if (!formState.managePlanNodeEntity.length) {
        message.error('请添加至少一个管理节点')
        return
      }
      // 表单校验失败
      modelForm.value.scrollToField(e.errorFields[0].name, {
        behavior: 'smooth',
        block: 'center'
      })
    })
}
const cancelProgramme = () => {
  toolOpen.value = false
  modal.open = true
}
const saveProgramme = () => {
  let params = _.cloneDeep(formState)
  params.managePlanNodeEntity
    .sort((f1, f2) => f1.pathDay - f2.pathDay)
    .map((v) => {
      v.behaviorJson = JSON.stringify(v.behaviorJson)
    })
  params.planName = programmeName.value
  params.groupId = props.groupId
  params.id = null
  PlanSave(params)
    .then((res) => {
      message.success('关联成功')
      let param = {
        limit: 10,
        page: 1,
        planName: programmeName.value
      }
      getPlanList(param).then((res) => {
        let item = res.data.list[0]
        const obj = _.cloneDeep(item)
        obj.managePlanNodeEntity.map((v) => {
          v.behaviorJson = JSON.parse(v.behaviorJson)
        })
        formState_reset(obj)
        toolOpen.value = false
        // modal.open = true
        programmeName.value = ''
      })
    })
    .catch((e) => {
      modal.loading = false
    })
}
// 校验部分
const validator_offset = async (_, value) => {
  if (value) {
    const reg = new RegExp(/([1-9][0-9]{0,}$)/)
    if (!reg.test(value)) {
      return Promise.reject('请输入大于0的天数')
    }
    if (!formState.unit) {
      return Promise.reject('请选择单位')
    }
  }
  return
}

const validator_node = async (_, value) => {
  const reg = new RegExp(/([1-9][0-9]{0,}$)/)
  if (!reg.test(value.pathDay)) {
    return Promise.reject('请输入大于0的天数')
  }

  const pathDay = new Set(Array.from(formState.managePlanNodeEntity.map((v) => v.pathDay)))
  if (pathDay.size < formState.managePlanNodeEntity.length) {
    return Promise.reject('管理路径时间不能重复')
  }

  const f = value.behaviorJson.some((v) => {
    return v.type && v.template_id && v.template_name
  })
  if (!f) {
    return Promise.reject('请完善管理行为')
  }
  if (value.behaviorJson.length > 1) {
    const noData = value.behaviorJson.filter((v) => !v.template_id)
    if (noData.length > 0) {
      return Promise.reject('请完善管理行为')
    }

    const set = new Set(Array.from(value.behaviorJson.map((v) => v.template_id)))
    if (set.size < value.behaviorJson.length) {
      return Promise.reject('管理行为不能重复')
    }
  }
  return Promise.resolve()
}

defineExpose({
  init
})
</script>
<style lang="less" scoped>
.programme_date {
  float: right;
  margin-top: 4px;
  font-size: 14px;
  font-weight: 400;

  .date {
    color: #86909c;
  }

  .datetime {
    color: #1d2129;
    margin: 0 8px;
  }
}

.event_item {
  background: #e5e6eb;
  padding: 8px 16px;
  margin-top: 16px;

  span {
    float: right;
  }
}

.modelForm {
  .bar {
    border: 1px solid #e5e6eb;
    margin-bottom: 12px;
  }

  .node {
    background: #f7f8fa;
    margin: 0 0 10px;
    padding-bottom: 1px;

    .ant-form-item {
      margin-bottom: 8px;
    }
  }

  .red {
    color: #f56667;
  }

  .title {
    width: 100%;
    height: 32px;
    background: #f7f8fa;
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 500;
    color: #1d2129;
    line-height: 32px;
    padding: 0 16px;
  }

  .add {
    width: 1160px;
    height: 32px;
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 400;
    color: #165dff;
    line-height: 22px;
  }

  .icon-plus,
  .icon-del {
    font-size: 16px;
  }

  .icon-plus {
    color: #165dff;
  }

  .icon-del {
    color: #f53f3f;
  }
}

.row {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
}

::v-deep(.ant-modal-body) {
  max-height: 500px !important;
  overflow: auto !important;
}
</style>
